package com.maint.m.example

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.maint.m.BaseActivity
import com.maint.m.WebSocketService
import com.maint.m.WebSocketMessageType
import com.maint.m.SimpleWebSocketHandler

/**
 * WebSocket 使用示例类
 * 这个类展示了如何使用封装后的 WebSocketService
 */
class WebSocketUsageExampleActivity : BaseActivity() {

    private val TAG = "WebSocketExample"
    
    // 创建一个自定义WebSocket处理器
    private val webSocketHandler = object : SimpleWebSocketHandler {
        override fun onMessageReceived(type: WebSocketMessageType, message: String) {
            // 根据消息类型进行处理
            when (type) {
                WebSocketMessageType.CONNECTED -> {
                    logMessage("已连接")
                    Toast.makeText(this@WebSocketUsageExampleActivity, "WebSocket已连接", Toast.LENGTH_SHORT).show()
                }
                WebSocketMessageType.TICKET_UPDATE -> {
                    logMessage("收到工单更新: $message")
                    // 处理工单更新逻辑
                }
                WebSocketMessageType.OPERATION_STATUS -> {
                    logMessage("操作状态更新: $message")
                    // 处理操作状态逻辑
                }
                WebSocketMessageType.ERROR -> {
                    logMessage("错误: $message")
                    // 处理错误逻辑
                }
                WebSocketMessageType.UNKNOWN -> {
                    logMessage("未知消息: $message")
                    // 处理未知消息
                }
            }
        }

        override fun onConnectionChanged(connected: Boolean) {
            val status = if (connected) "已连接" else "未连接"
            logMessage("WebSocket连接状态: $status")
        }

        override fun onError(errorMsg: String) {
            logMessage("WebSocket错误: $errorMsg")
            Log.e(TAG, "错误: $errorMsg")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 简单起见，不使用布局文件
    }

    override fun onResume() {
        super.onResume()
        
        // 注册WebSocket处理器
        WebSocketService.getInstance().registerHandler(webSocketHandler)
        
        // 示例：发送普通文本消息
        // WebSocketService.getInstance().sendMessage("这是一条测试消息")
        
        // 示例：发送结构化消息
        // WebSocketService.getInstance().sendStructuredMessage(business = 1, data = "test_data")
    }

    override fun onDestroy() {
        super.onDestroy()
        
        // 注销WebSocket处理器，避免内存泄漏
        WebSocketService.getInstance().unregisterHandler(webSocketHandler)
    }

    // 记录日志
    private fun logMessage(message: String) {
        Log.d(TAG, message)
    }
}